#!/bin/bash
##########################################################################################
# Utility for backingup folders with rsync and have the log emailed
#
# Copyright © 2012 Balta Costel All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
#   list of conditions and the following disclaimer in the documentation and/or
#   other materials provided with the distribution.
# * Neither the name of Balta Costel nor the names of its contributors may be used to
#   endorse or promote products derived from this software without specific prior
#   written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##########################################################################################
# Dependencies 	
# sendEmail for sending logs via email
# http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
# perl Net::SSLeay for ssl sendEmail
# perl IO::Socket::SSL for ssl sendEmail
# openssh-clients (provides ssh client and ssh-copy-id)
# openssh (provides ssh-keygen)
# rsync (provides...ooh yeah...rsync)
# !!!NOTE!!!  you need to setup ssh key based autentication
# http://www.mdkdog.tk/index.php/doc-s/quick-ssh-key-based-auth-howto
##########################################################################################

. /etc/profile
##########################################################################################
######                     START CONFIGURATION SECTION                              ######
##########################################################################################
. /etc/profile
DATE=`date +%d-%m-%Y`
NOW=`date +%H:%M:%S`
HOSTNAME=`hostname -f`
LOG_FILE="/var/log/rsync.$DATE.log"
SRC_HOST="ip or hostname for source host"	# host you need to backup 
SRC_DIRS="/var/www,/etc,/home"				# comma-separated paths to backup
DST_DIR="/local/path/for/backup"           # where to backup !!!needs to have final slash

# ssh info (needed for rsync over ssh)
SSH_USER="ssh_user"                         # ssh user (need to have read rights on source files)
SSH_PORT="2233"                             # if target host is running ssh on custom port set here, else set "22"

# Email Configuration Section
EMAIL_FROM="backup_user@domain.com"
EMAIL_TO="admin@domain.com"
EMAIL_SUBJ="Rsync log from $HOSTNAME"
SMTP_SRV="mail.domain.com:smtp_port"
SMTP_USER="smtp_username"
SMTP_PASS="smtp_password"

##########################################################################################
######                     END CONFIGURATION SECTION                                ######
##########################################################################################

# FUNCTION that check and install dependencies as needed
#------------------------------ START FUNCTION ------------------------------------------#
function check_deps() {
# install openssh-clients (provides ssh client and ssh-copy-id)
if ! builtin type -p ssh &>/dev/null; then
	echo "openssh-clients is not installed. installing..." >> ${LOG_FILE}
	yum -y -q install openssh-clients
fi
# verify install of openssh-clients
if ! builtin type -p ssh &>/dev/null; then
	echo "Something went wrong. try installing openssh-clients manually " >> ${LOG_FILE}
	return 1
	exit 1
fi

# install openssh (provides ssh-keygen)
if ! builtin type -p ssh-keygen &>/dev/null; then
	echo "openssh is not installed. installing..." >> ${LOG_FILE}	
	yum -y -q install openssh 
fi
# verify install of openssh
if ! builtin type -p ssh-keygen &>/dev/null; then
	echo "Something went wrong. try installing openssh manually " >> ${LOG_FILE}
	return 1
	exit 1
fi

# install rsync
if ! builtin type -p rsync &>/dev/null; then
	echo "rsync is not installed. installing..." >> ${LOG_FILE}	
	yum -y -q install rsync 
fi
# verify install of rsync
if ! builtin type -p rsync &>/dev/null; then
	echo "Something went wrong. try installing rsync manually " >> ${LOG_FILE}
	return 1
	exit 1
fi

if ! perl -MNet::SSLeay -e '' &>/dev/null; then
	echo " perl-Net-SSLeay is not installed. installing..." >> ${LOG_FILE}	
	yum -y -q install perl-Net-SSLeay
fi
# verify install
if ! perl -MNet::SSLeay -e '' &>/dev/null; then
	echo " Something went wrong. try installing perl-Net-SSLeay manually " >> ${LOG_FILE}
	return 1
	exit 1
fi

if ! perl -MIO::Socket::SSL -e '' &>/dev/null; then
	echo " perl-IO-Socket-SSL is not installed. installing..." >> ${LOG_FILE}	
	yum -y -q install perl-IO-Socket-SSL
fi
# verify install
if ! perl -MIO::Socket::SSL -e '' &>/dev/null; then
	echo " Something went wrong. try installing perl-IO-Socket-SSL manually " >> ${LOG_FILE}
	return 1
	exit 1
fi

if ! builtin type -p sendEmail &>/dev/null; then
	echo " sendEmail is not installed. installing..." >> ${LOG_FILE}	
	wget -q -O /tmp/sendEmail-v1.56.tar.gz http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
	tar -zxf /tmp/sendEmail-v1.56.tar.gz -C /tmp/
	cp /tmp/sendEmail-v1.56/sendEmail /usr/bin/
	cp /tmp/sendEmail-v1.56/sendEmail.pl /usr/bin/
fi
# verify install
if ! builtin type -p sendEmail &>/dev/null; then
	echo " Something went wrong. try installing sendEmail manually " >> ${LOG_FILE}
	return 1
	exit 1
fi
}
#------------------------------ END FUNCTION --------------------------------------------#

#----- start doing stuff
# if log exist rename
if [ -f "${LOG_FILE}" ]; then
	mv -f $LOG_FILE $LOG_FILE.old
fi
# start logging
echo "===== RUN START on ${DATE} at `date +%H:%M:%S` =======" >> ${LOG_FILE}	
# call check_deps
check_deps
if [ $? -gt 0 ]; then
        echo "dependency checking failed. Aborting backup." >> ${LOG_FILE}
		send_email
		exit 0
fi

echo "===== RSYNC START on ${DATE} at `date +%H:%M:%S` =====" >> ${LOG_FILE}
rsync -az --stats --delete -e "ssh -p ${SSH_PORT}" $SSH_USER@$SRC_HOST:{$SRC_DIRS} $DST_DIR/ >> ${LOG_FILE}
echo "===== RSYNC END on ${DATE} at `date +%H:%M:%S` =======" >> ${LOG_FILE}

# FUNCTION Send email
#------------------------------ START FUNCTION ------------------------------------------#
function send_email(){
echo "######### Emailing the system administrator. #########" >> ${LOG_FILE}
sendEmail \
		-f $EMAIL_FROM \
		-t $EMAIL_TO \
		-u $EMAIL_SUBJ \
		-s $SMTP_SRV \
		-xu $SMTP_USER \
		-xp $SMTP_PASS \
		-o message-file=$LOG_FILE \
		-o tls=yes \
		-q -l /var/log/sendEmail.log
}
#------------------------------ END FUNCTION --------------------------------------------#
echo "===== RUN END on ${DATE} at `date +%H:%M:%S` =========" >> ${LOG_FILE}
# end logging
send_email
